﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace ModeloGaleriaNET
{
    public class AESCripto
    {
        private readonly byte[] testKey = Encoding.UTF8.GetBytes(new char[] { 'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' });
        private AesManaged aesAlg;

        public AESCripto()
        {
            aesAlg = new AesManaged()
            {
                Mode = CipherMode.ECB,
                Padding = PaddingMode.ISO10126,
                IV = testKey,
                Key = testKey
            };
        }

        public AESCripto(byte[] key)
        {
            aesAlg = new AesManaged()
            {
                Mode = CipherMode.ECB,
                Padding = PaddingMode.ISO10126,
                IV = key,
                Key = key
            };
        }

        public byte[] EncryptStringToBytes(string plainText)
        {
            byte[] encrypted;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
            // Return the encrypted bytes from the memory stream.
            return encrypted;
        }

        public string DecryptStringFromBytes(byte[] cipherText)
        {
            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            return plaintext;
        }
    }
}
